<template>
  <div class="container">
    <div>
      <el-button
        type="primary"
        size="mini"
        icon="el-icon-plus"
        @click="openDialog('新增')"
      >新增</el-button>
      <el-button
        type="danger"
        size="mini"
        class="el-icon-delete"
        :disabled="multipleSelection.length == 0"
        @click="deletes()"
      >删除</el-button>
      <el-button
        type="warning"
        size="mini"
        class="el-icon-download"
      >导出</el-button>
    </div>
    <el-table
      :data="tableData"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        align="center"
        type="selection"
        width="55"
      />
      <el-table-column
        label="角色名称"
        align="center"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.roleName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="权限标识"
        align="center"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.roleKey }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="状态"
        align="center"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.isBanned == "0" ? "正常" : "禁用" }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdOn) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="mini"
            icon="el-icon-edit"
            @click="openEtidDialog('修改', scope.row)"
          >编辑</el-button>
          <el-button
            type="text"
            size="mini"
            icon="el-icon-delete"
            @click="deleteRow(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      class="pagination"
      background
      :current-page="queryParams.pageIndex"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="queryParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <el-dialog
      :title="dialogSetting.title"
      :visible.sync="dialogSetting.dialogVisible"
      :width="dialogSetting.width"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :before-close="beforeCloseDialog"
    >
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        label-width="80px"
        :rules="rules"
      >
        <el-form-item
          label="角色名称"
          prop="roleName"
        >
          <el-input v-model="ruleForm.roleName" />
        </el-form-item>
        <el-form-item
          label="权限字符"
          prop="roleKey"
        >
          <el-input v-model="ruleForm.roleKey" />
        </el-form-item>
        <el-form-item
          v-if="dialogSetting.title === '修改'"
          label="状态"
          prop="isBanned"
        >
          <el-radio-group v-model="ruleForm.isBanned">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-tree
            ref="menu"
            :data="treeData"
            show-checkbox
            node-key="id"
            empty-text="加载中，请稍后"
            :props="defaultProps"
          />
        </el-form-item>
        <el-form-item
          label="备注"
          prop="remark"
        >
          <el-input
            v-model="ruleForm.remark"
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          size="small"
          @click="closeDialog()"
        >取 消</el-button>
        <el-button
          type="primary"
          size="small"
          @click="sub('ruleForm')"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  create,
  getPageList,
  deletesRole,
  roleDetailById,
  update
} from '@/api/upms/role'
import { getListTree } from '@/api/upms/menu'
export default {
  name: 'Role',
  data() {
    return {
      // 查询参数
      queryParams: {
        pageIndex: 1,
        pageSize: 10,
        jobName: '',
        isBanned: ''
      },
      treeData: [],
      tableData: [],
      total: 0,
      multipleSelection: [], // 选项集合
      dialogSetting: {
        dialogVisible: false,
        title: '',
        width: '30%'
      },
      ruleForm: {
        id: null,
        roleName: '',
        roleKey: '',
        remark: '',
        isBanned: '0'
      },
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleKey: [
          { required: true, message: '请输入权限字符', trigger: 'blur' }
        ],
        isBanned: [{ required: true, message: '请选择状态', trigger: 'change' }]
      },
      defaultProps: {
        children: 'children',
        label: 'menuTitle',
        id: 'id'
      }
    }
  },
  created() {
    this.getPageList()
  },
  methods: {
    // 获取分页列表
    getPageList() {
      getPageList(this.queryParams).then(resp => {
        if (resp.code === 0) {
          this.tableData = resp.data.list
          this.total = resp.data.totalRows
        }
      })
    },
    // 每页条目数变化
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getPageList()
    },
    // 页数变化
    handleCurrentChange(val) {
      this.queryParams.pageIndex = val
      this.getPageList()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    openDialog(title) {
      this.dialogSetting.title = title
      this.dialogSetting.dialogVisible = true
      this.getListTree()
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    beforeCloseDialog(done) {
      this.resetForm('ruleForm')
      this.reset()
      done()
    },
    openEtidDialog(title, rowId) {
      // 获取详情
      this.getDetail(rowId)
    },
    getDetail(row) {
      roleDetailById({ id: row.id }).then(resp => {
        if (resp.code === 0) {
          const rowDetail = resp.data.detail
          this.ruleForm.id = rowDetail.id
          this.ruleForm.roleKey = rowDetail.roleKey
          this.ruleForm.roleName = rowDetail.roleName
          this.ruleForm.isBanned = rowDetail.isBanned
          this.ruleForm.remark = rowDetail.remark
          this.getListTree()
          this.dialogSetting.title = '修改'
          this.dialogSetting.dialogVisible = true
          this.$nextTick(function() {
            this.$refs.menu.setCheckedKeys(rowDetail.menuds)
          })
        }
      })
    },
    closeDialog() {
      this.dialogSetting.dialogVisible = false
      this.resetForm('ruleForm')
      this.reset()
    },
    reset() {
      this.ruleForm.id = null
      this.ruleForm.roleName = ''
      this.ruleForm.roleKey = ''
      this.ruleForm.remark = ''
      this.ruleForm.isBanned = '0'
      this.$refs.menu.setCheckedKeys([])
    },
    getListTree() {
      getListTree().then(resp => {
        if (resp.code === 0) {
          this.treeData = resp.data.list
          // this.deptOptions = []
          // const dept = { id: '0', menuTitle: '根节点', children: [] }
          // dept.children = resp.data.list
          // this.deptOptions.push(dept)
        }
      })
    },
    // 所有部门节点数据
    getDeptAllCheckedKeys() {
      // 目前被选中的部门节点
      const checkedKeys = this.$refs.menu.getHalfCheckedKeys()
      // 半选中的部门节点
      const halfCheckedKeys = this.$refs.menu.getCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    // 批量删除
    deletes() {
      var arr = []
      this.multipleSelection.forEach(v => {
        arr.push(v['id'])
      })
      deletesRole({ ids: arr }).then(resp => {
        if (resp.code === 0) {
          this.getPageList()
        }
      })
    },
    deleteRow(row) {
      deletesRole({ ids: [row.id] }).then(resp => {
        if (resp.code === 0) {
          this.getPageList()
        }
      })
    },
    sub(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          switch (this.dialogSetting.title) {
            case '新增':
              var createParam = {
                roleName: this.ruleForm.roleName,
                roleKey: this.ruleForm.roleKey,
                remark: this.ruleForm.remark,
                menuIds: this.getDeptAllCheckedKeys()
              }
              create(createParam).then(resp => {
                if (resp.code === 0) {
                  this.notifySuccess('创建成功')
                  this.closeDialog()
                  this.getPageList()
                }
              })
              break
            case '修改':
              var updateParam = {
                id: this.ruleForm.id,
                isBanned: this.ruleForm.isBanned,
                remark: this.ruleForm.remark,
                menuIds: this.getDeptAllCheckedKeys()
              }
              update(updateParam).then(resp => {
                if (resp.code === 0) {
                  this.notifySuccess('修改成功')
                  this.closeDialog()
                  this.getPageList()
                }
              })
              break
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
@import "~@/styles/common.scss";
</style>
